<template>
  <div class="mainAlbum">
    <!--操作按钮-->
    <div style="height: 40px;display: flex;flex-direction: row;justify-content: flex-start;align-items: center">
      <div class="slidedown">
        <p class="innerit el-icon-lx-tag" @click="centerDialogVisibleCreat=true"> 创建相册~</p>
      </div>
      <div class="slidedown" @click="uploadPicture" style="margin-left: 10px">
        <p class="innerit el-icon-lx-tag"> 上传照片~</p>
      </div>
    </div>
    <!--操作按钮end-->

    <!--相册显示-->
    <div class="showAlbum">
      <div class="up">
        <div class="allAlbum" style="position: relative" @click="toShow('x')">
            <span :class="{font_set_all:true,colorDark:!allAlbumCheck,colorWhite:allAlbumCheck}"
                  style="font-size: large;font-weight: bolder;font-family: 宋体;">全部相片</span>
          <img style="height: 100%;width: 100%" :src="allAlbumFirstMsg.imgSrc"/>
        </div>
<!--        <div class="allAlbum"></div>-->
      </div>
      <div class="down">
        <div class="imgContainer" v-for="item in albumMsg" :key="item.id" @click="toShow(item.id)"
             @contextmenu.prevent="del(item.id)">
          <span :class="{font_set:true,colorDark:item.coverPath==null,colorWhite:item.coverPath!=null}"
                style="font-size: large;font-weight: bolder;font-family: 宋体;">{{ item.bagName }}</span>
          <img style="height: 100%;width: 100%" :src="item.imgSrc"/>
        </div>
      </div>
    </div>
    <!--相册显示end-->

    <!--上传相册模态框-->
    <el-dialog
        title="上传照片"
        :visible.sync="centerDialogVisible"
        width="90%"
        center>
      <div style="width: 100%;">
        <el-form style="width: 40%">
          <el-form-item label="选择相册">
            <el-select v-model="albumId" placeholder="请选择上传相册">
              <el-option label="" value=""></el-option>
              <el-option v-for="item in bagArr" :key="item.id" :label="item.bagName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!--输入定位废案-->
        <!--        <el-form style="width: 25%">-->
        <!--          <el-form-item>-->
        <!--            <el-input placeholder="请输入内容" v-model="inputSearchVal" class="input-with-select">-->
        <!--              <el-select v-model="select" slot="prepend" placeholder="请选择" :disabled="isDisabled">-->
        <!--                <el-option value=""></el-option>-->
        <!--                <el-option v-for="(item,index) in selectList" :key="index"-->
        <!--                           :value="item.address" :label="item.name">{{ item.name }}-->
        <!--                </el-option>-->
        <!--              </el-select>-->
        <!--              <el-button slot="append" icon="el-icon-search" @click="searchKeyword"></el-button>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-form>-->
      </div>
      <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          ref="upload"
          :limit="limit"
          :on-exceed="moreout"
          :on-change="handleChange"
          :multiple="true"
          style="height: 148px;border: 1px dashed #eaeaea;padding: 5px;margin-top: 10px;">
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img
              class="el-upload-list__item-thumbnail"
              :src="file.url" alt=""
          >
          <span class="el-upload-list__item-actions">
          <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
          >
          <i class="el-icon-zoom-in"></i>
          </span>
          <span
              v-if="!disabled"
              class="el-upload-list__item-delete"
              @click="handleRemove(file)"
          >
            <i class="el-icon-delete"></i>
          </span>
         </span>
        </div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="upload">确 定</el-button>
      </span>
    </el-dialog>
    <!--上传相册模态框end-->
    <!--创建相册模态框-->
    <el-dialog
        title="创建相册"
        :visible.sync="centerDialogVisibleCreat"
        width="40%"
        center>
      <el-form ref="form" label-width="80px">
        <el-form-item label="相册名称">
          <el-input v-model="input" placeholder="请输入相册名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisibleCreat = false">取 消</el-button>
        <el-button type="primary" @click="creat">确 定</el-button>
      </span>
    </el-dialog>
    <!--创建相册模态框end-->
  </div>
</template>

<script>
import AMap from 'AMap'

export default {
  name: "Album",
  data: function () {
    return {
      limit: 9,
      dialogImageUrl: '',
      filearr: [],
      disabled: false,
      param: null,
      centerDialogVisible: false,
      centerDialogVisibleCreat: false,
      albumId: "",
      bagArr: [],
      inputSearchVal: "",
      select: "",
      selectList: [],
      isDisabled: true,
      lngAdLat: "",
      input: "",
      albumMsg: [],
      allAlbumFirstMsg: {},
      allAlbumCheck: false
    }
  },
  mounted() {
    this.bagCheck()
    this.init();
    this.getAlbum()
    this.selectNewestByFid()
  },
  methods: {
    selectNewestByFid() {
      this.$http.get("/album/selectNewestByFid").then(data => {
        if (data.data != null) {
          this.allAlbumCheck = true
        }
        let res = data.data
        this.getimg(res.id).then(ret => {
          res.imgSrc = ret
        })
        this.allAlbumFirstMsg = res
      })
    },
    toShow(id) {
      this.$router.push({
        path: `/albumShow/${id}`,
      })
    },
    bagCheck() {
      this.$http.get("/album/selectAllBagInFamily").then(data => {
        this.bagArr = data.data
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete("/album/deleteBag/" + id).then(data => {
          if (data.code == 200) {
            this.$message.success("相册删除成功")
            this.getAlbum()
            this.bagCheck()
            this.selectNewestByFid()
            this.albumId = ""
          } else {
            this.$message.error(data.message)
            this.getAlbum()
            this.bagCheck()
            this.selectNewestByFid()
            this.albumId = ""
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    async getAlbum() {
      await this.$http.get("/album/selectAllBagInFamily").then(async data => {
        // //console.log(data)
        let more = data.data
        for (let i = 0; i < more.length; i++) {
          if (more[i].coverPath != null) {
            await this.getimg(more[i].coverPath).then(data => {

              more[i].imgSrc = data
            })
          } else {
            more[i].imgSrc = require("../assets/空页面.png")
          }
        }
        this.albumMsg = more
      })
    },
    getimg(id) {
      return new Promise(resolve => {
        this.$http({
          url: "/album/albumDownloadCompress/" + id,
          method: "get",
          responseType: "arraybuffer",
        }).then(res => {
          let bytes = new Uint8Array(res);
          let storeData = "";
          let len = bytes.byteLength;
          for (let i = 0; i < len; i++) {
            storeData += String.fromCharCode(bytes[i]);
          }
          let database = "data:image/png;base64," + window.btoa(storeData);
          resolve(database);
        });
      })
    },
    creat() {
      if (this.input == "") {
        this.$message.error("请输入相册名称")
        return
      }
      this.$http.post("/album/insertBag", {bagName: this.input}).then(data => {
        //console.log(data)
        if (data.code == 200) {
          this.$message.success("创建成功")
          this.input = ""
          this.centerDialogVisibleCreat = false
          this.getAlbum()
          this.bagCheck()
          this.selectNewestByFid()
        }
      })
    },
    init() {
      var that = this
      let mapObj = new AMap.Map('iCenter');
      let geolocation;
      mapObj.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          maximumAge: 0,           //定位结果缓存0毫秒，默认：0
          convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
          showButton: true,        //显示定位按钮，默认：true
          buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
          buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
          showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
          panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
          zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        mapObj.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', that.onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', that.onError);      //返回定位出错信息
      });
    },
    onComplete(e) {
      this.lngAdLat = e.position.lng + "," + e.position.lat
    },
    onError() {
      //console.log(e)
    },
    upload() {
      if (this.albumId == "") {
        this.$message.error("请选择相册")
        return
      }
      this.param = new FormData()
      this.filearr.forEach((file) => {
        this.param.append(`file`, file) // 把单个文件重命名，存储起来（给后台）
      })

      this.$http({
        method: "post",
        url: "/album/insertPicture/" + this.albumId + "/" + this.lngAdLat,
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        data: this.param
      }).then(data => {
        //console.log(data)
        if (data.code == 200) {
          this.$message.success("发表成功！！")
          this.$refs.upload.clearFiles();
          this.getAlbum()
          this.selectNewestByFid()
          this.filearr = []
          this.param = null
          this.albumId = ""
          this.centerDialogVisible = false
        }
      })
    },
    uploadPicture() {
      this.centerDialogVisible = true
    },
    handleChange(file) {
      const fileObj = file.raw;
      if (file && fileObj) {
        this.filearr.push(fileObj)
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
    },
    moreout() {
      this.$message.warning("最多上传九张照片！")
    },
    handleRemove(file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      fileList.splice(index, 1);

      let aList = this.filearr
      let aIndex = aList.findIndex(fileItem => {
        return fileItem.uid === file.uid
      });
      this.filearr.splice(aIndex, 1)
    },
    /** 初始化搜索工具 */
    mapSearchInit() {
      // let that = this;
      // // 绑定自动提示
      // AMap.plugin(['AMap.Autocomplete', 'AMap.PlaceSearch'], function () {
      //   var autoOptions = {
      //     input: "tipInput",
      //     city: '北京',
      //   }
      //   var autoCompleteComponent = new AMap.Autocomplete(autoOptions);
      //   // 监听选中项
      //   AMap.event.addListener(autoCompleteComponent, "select", function (data) {
      //     //console.log(data);
      //     if (data.poi.location != undefined) {
      //       //定位到中心点
      //       //console.log("定位中心点")
      //       that.map.setCenter(data.poi.location);
      //     }
      //   })
      //   that.autoCompleteComponent = autoCompleteComponent;
      //   // 注册placeSearch组件
      //   that.placeSearchComponent = new AMap.PlaceSearch({
      //     // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
      //     city: '北京'
      //   })
      // });
    },
    /** 关键词搜索 */
    searchKeyword() {
      this.isDisabled = false
      let that = this
      this.placeSearchComponent.search(this.inputSearchVal, function (status, result) {
        // 查询成功时，result即对应匹配的POI信息
        //console.log(result.poiList.pois);
        //console.log(result);
        let arr = result.poiList.pois
        let arr2 = []
        for (let i = 0; i < arr.length; i++) {
          let str = {
            address: arr[i].address,
            name: arr[i].name
          }
          arr2.push(str)
        }
        that.selectList = JSON.parse(JSON.stringify(arr2))
      })


    }
  }
}
</script>

<style scoped>
.showAlbum {
  height: 700px;
  box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
  border-radius: 10px;
  margin-top: 10px;
}

.allAlbum {
  height: 200px;
  width: 35%;
  margin-left: 15px;
  margin-top: 15px;
  box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  border-radius: 10px;
  cursor: pointer;
}

.up {
  height: 250px;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: left;
  align-items: center;
  flex-wrap: wrap;
  /*background-color: #eaeaea;*/
}

.down {
  /*height: 450px;*/
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  flex-wrap: wrap;
  overflow: auto;
  border-top: 1px dashed #eaeaea;
}

.imgContainer {
  height: 110px;
  width: 18%;
  margin-left: 15px;
  margin-top: 15px;
  margin-bottom: 15px;
  /*border: 1px dashed #eaeaea;*/
  position: relative;
  box-shadow: rgba(0, 0, 0, 0.12) 0px 1px 3px, rgba(0, 0, 0, 0.24) 0px 1px 2px;
  border-radius: 10px;
  cursor: pointer;
  transition-duration: 0.5s;
}

/*.imgContainer :hover {*/
/*  height: 110px;*/
/*  width: 18%;*/
/*  margin-left: 15px;*/
/*  margin-top: 15px;*/
/*  margin-bottom: 15px;*/
/*  !*border: 1px dashed #eaeaea;*!*/
/*  position: relative;*/
/*  box-shadow: rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px;*/
/*  border-radius: 10px;*/
/*  cursor: pointer;*/
/*}*/

img {
  border-radius: 10px;
}

.font_set {
  position: absolute;
  top: 80px;
  left: 10px;
}

.font_set_all {
  position: absolute;
  top: 160px;
  left: 20px;
}

.colorWhite {
  color: #ffffff;
}

.colorDark {
  color: #2c3e50;
}

.mainAlbum {
  width: 980px;
  float: right;
}

.el-upload {
  float: right;
  clear: both;
  margin-right: 10px;
}

.slidedown {
  height: 40px;
  width: 100px;
  background-color: rgb(241, 248, 239);
  border-radius: 10px;
  cursor: pointer;
  line-height: 40px;
  text-align: center;
  /*position: relative;*/
}

.innerit {
  color: #e0c6a7;
}

.el-select .el-input {
  width: 200px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>